package com.hean.util;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.hean.entity.Contact;

public class DB extends SQLiteOpenHelper {

	public DB(Context ctx) {
		super(ctx, "hean", null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("create table t_contact (_id integer primary key autoincrement, name varchar(50), phone varchar(50))");
		db.execSQL("insert into t_contact (name,phone) values('黄河大虾','12345678901')");

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if(oldVersion==1&&newVersion==2){
			db.execSQL("...");
		}
	}

	/**
	 * 
	 * @return
	 */
	public Cursor findAllContacts() {
		SQLiteDatabase db = getReadableDatabase();
		Cursor cursor = db.rawQuery("select _id, name, phone from t_contact",
				null);
//		db.rawQuery("select _id, name, phone from t_contact where name=?", new String[]{String.valueOf(1)});
		return cursor;
	}

	/**
	 * 
	 * @param contact
	 */
	public void insertContacts(Contact contact) {
		SQLiteDatabase db = getWritableDatabase();
		db.beginTransaction();
		try {
			db.execSQL("insert into t_contact(name,phone) values('"
					+ contact.getName() + "','" + contact.getPhone() + "')");
			db.execSQL("insert into t_contact(name,phone) values(?,?)", new Object[]{"hean","110"});
			db.setTransactionSuccessful();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		db.endTransaction();//db.setTransactionSuccessful();未执行则回滚事务
		db.close();//单用户，也可以不关，可以在程序启动时打开连接，程序关闭时，关闭连接,实际上是因为getWritableDatabase()得到的是同一个对象
	}
	
	public void deleteContact(int id) {
		SQLiteDatabase db = getWritableDatabase();
		db.execSQL("delete from t_contact where _id=" + id);
	}

}
